    package com.summer.dao.user;

    import com.mysql.jdbc.StringUtils;
import com.summer.dao.BaseDao;
import com.summer.pojo.User;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

    /**
     * 作者:夏天
     * qq:1205232048
     */
    public class UserDaoImpl implements UserDao{

        /**
         * 根据连接 用户编码 返回用户
         * @param connection
         * @param userCode
         * @return
         */
        public User getLoginUser(Connection connection, String userCode){

            PreparedStatement preparedStatement = null;
            ResultSet resultSet = null;
            User user = null;

            if(connection != null){
                String sql = "select * from smbms_user where userCode = ?";
                Object[] params = {userCode};

                try {
                    resultSet = BaseDao.execute(connection, preparedStatement, resultSet, sql, params);
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
                try {
                    if(resultSet.next()){
                        user = new User();
                        user.setId(resultSet.getInt("id"));
                        user.setUserCode(resultSet.getString("userCode"));
                        user.setUserName(resultSet.getString("userName"));
                        user.setUserPassword(resultSet.getString("userPassword"));
                        user.setGender(resultSet.getInt("gender"));
                        user.setBirthday(resultSet.getDate("birthday"));
                        user.setPhone(resultSet.getString("phone"));
                        user.setAddress(resultSet.getString("address"));
                        user.setUserRole(resultSet.getInt("userRole"));
                        user.setCreatedBy(resultSet.getInt("createdBy"));
                        user.setCreationDate(resultSet.getDate("creationDate"));
                        user.setModifyBy(resultSet.getInt("modifyBy"));
                        user.setModifyDate(resultSet.getDate("modifyDate"));

                    }
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
                BaseDao.closeResource(connection,preparedStatement,resultSet);
            }
            return user;
        }

        /**
         * 根据连接 用户id 用户新密码 返回修改密码结果
         * @param connection
         * @param id
         * @param newpassword
         * @return
         * @throws Exception
         */
        public int modifyPasswordById(Connection connection, int id, String newpassword) throws Exception{

            PreparedStatement preparedStatement = null;
            int execute = 0;//存放sql执行结果用来返回

            //如果连接不为空
            if(connection != null){
                String sql = "update smbms_user set userPassword = ? where id = ?";
                Object params[] = {newpassword,id};
                try {
                    execute = BaseDao.execute(connection, preparedStatement, sql, params);
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
                BaseDao.closeResource(null,preparedStatement,null);
            }
            return execute;
        }

        /**
         * 根据连接 用户姓名 用户角色 返回用户数量
         * @param connection
         * @param userName
         * @param userRole
         * @return
         * @throws Exception
         */
        public int getUserCount(Connection connection,String userName,int userRole) throws Exception{
            PreparedStatement preparedStatement = null;
            ResultSet resultSet = null;
            int userCount = 0;

            if(connection != null){
                StringBuffer sql = new StringBuffer();
                sql.append("select COUNT(1) as userCount from smbms_user u,smbms_role r where u.userRole = r.id");
                //创建一个list来存放我们的参数
                ArrayList<Object> paramsList = new ArrayList<Object>();
                if(!StringUtils.isNullOrEmpty(userName)){
                    sql.append(" and u.userName like ?");
                    paramsList.add("%" + userName + "%");
                }
                if(userRole > 0){
                    sql.append(" and r.id = ?");
                    paramsList.add(userRole);
                }
                Object[] params = paramsList.toArray();
                try {
                    resultSet = BaseDao.execute(connection, preparedStatement, resultSet, sql.toString(), params);
                    if(resultSet.next()){
                        userCount = resultSet.getInt("userCount");
                    }
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                } finally {
                    BaseDao.closeResource(connection,preparedStatement,resultSet);
                }
            }
            return userCount;
        }

        /**
         * 根据连接 用户姓名 用户角色 当前页数 页面大小 返回用户列表
         * @param connection
         * @param userName
         * @param userRole
         * @param currentPageNo
         * @param pageSize
         * @return
         */
        public List<User> getUserList(Connection connection, String userName, int userRole, int currentPageNo, int pageSize){
            PreparedStatement preparedStatement = null;
            List<User> users = new ArrayList<User>();
            ResultSet resultSet = null;

            if(connection != null){
                StringBuffer sql = new StringBuffer();
                sql.append("select u.*,r.roleName as userRoleName from smbms_user u,smbms_role r where u.userRole = r.id");
                List<Object> list = new ArrayList<Object>();
                if(!StringUtils.isNullOrEmpty(userName)){
                    sql.append(" and u.userName like ?");
                    list.add("%" + userName + "%");
                }
                if(userRole > 0){
                    sql.append(" and u.userRole = ?");
                    list.add(userRole);
                }
                //在mysql数据库中，分页使用 limit startIndex，pageSize ; 总数
                sql.append(" order by creationDate DESC limit ?,?");
                currentPageNo = (currentPageNo - 1) * pageSize;
                list.add(currentPageNo);
                list.add(pageSize);
                System.out.println("UserDaoImpl->getUserList->userName = " + userName);
                System.out.println("UserDaoImpl->getUserList->userRole = " + userRole);
                System.out.println("UserDaoImpl->getUserList->sql = " + sql);
                Object[] params = list.toArray();
                try {
                    resultSet = BaseDao.execute(connection, preparedStatement, resultSet, sql.toString(), params);
                    while (resultSet.next()){
                        User _user = new User();
                        _user.setId(resultSet.getInt("id"));
                        _user.setUserCode(resultSet.getString("userCode"));
                        _user.setUserName(resultSet.getString("userName"));
                        _user.setGender(resultSet.getInt("gender"));
                        _user.setBirthday(resultSet.getDate("birthday"));
                        _user.setPhone(resultSet.getString("phone"));
                        _user.setUserRole(resultSet.getInt("userRole"));
                        _user.setUserRoleName(resultSet.getString("userRoleName"));
                        users.add(_user);
                    }
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                } finally {
                    BaseDao.closeResource(connection,preparedStatement,resultSet);
                }
            }
            return users;
        }

        /**
         * 根据连接 用户 返回添加结果
         * @param connection
         * @param user
         * @return int
         * @throws Exception
         */
        public int addUser(Connection connection,User user) throws Exception {
            PreparedStatement preparedStatement = null;
            int execute = 0;
            if(connection != null){
                String sql = "insert into smbms_user " +
                        "(userCode,userName,userPassword,userRole,gender,birthday,phone,address,creationDate,createdBy) " +
                        "values(?,?,?,?,?,?,?,?,?,?)";
                Object[] params = {user.getUserCode(), user.getUserName(), user.getUserPassword(),
                        user.getUserRole(), user.getGender(), user.getBirthday(),
                        user.getPhone(), user.getAddress(), user.getCreationDate(), user.getCreatedBy()};
                execute = BaseDao.execute(connection, preparedStatement, sql, params);
                BaseDao.closeResource(null,preparedStatement,null);
            }
            return execute;
        }

        /**
         * 根据连接 用户Id 返回用户
         * @param connection
         * @param id
         * @return User
         * @throws Exception
         */
        public User getUserById(Connection connection, String id) throws Exception {
            User user = null;
            PreparedStatement pstm = null;
            ResultSet rs = null;
            if (null != connection) {
                String sql = "select u.*,r.roleName as userRoleName from smbms_user u,smbms_role r where u.id=? and u.userRole = r.id";
                Object[] params = {id};
                rs = BaseDao.execute(connection, pstm, rs, sql, params);
                if (rs.next()) {
                    user = new User();
                    user.setId(rs.getInt("id"));
                    user.setUserCode(rs.getString("userCode"));
                    user.setUserName(rs.getString("userName"));
                    user.setUserPassword(rs.getString("userPassword"));
                    user.setGender(rs.getInt("gender"));
                    user.setBirthday(rs.getDate("birthday"));
                    user.setPhone(rs.getString("phone"));
                    user.setAddress(rs.getString("address"));
                    user.setUserRole(rs.getInt("userRole"));
                    user.setCreatedBy(rs.getInt("createdBy"));
                    user.setCreationDate(rs.getTimestamp("creationDate"));
                    user.setModifyBy(rs.getInt("modifyBy"));
                    user.setModifyDate(rs.getTimestamp("modifyDate"));
                    user.setUserRoleName(rs.getString("userRoleName"));
                }
                BaseDao.closeResource(null, pstm, rs);
            }
            return user;
        }

        /**
         * 根据连接 用户 返回用户修改结果
         * @param connection
         * @param user
         * @return
         * @throws Exception
         */
        public int modifyUser(Connection connection, User user) throws Exception {
            int flag = 0;
            PreparedStatement pstm = null;
            if (null != connection) {
                String sql = "update smbms_user set userName=?," +
                        "gender=?,birthday=?,phone=?,address=?,userRole=?,modifyBy=?,modifyDate=? where id = ? ";
                Object[] params = {user.getUserName(), user.getGender(), user.getBirthday(),
                        user.getPhone(), user.getAddress(), user.getUserRole(), user.getModifyBy(),
                        user.getModifyDate(), user.getId()};
                flag = BaseDao.execute(connection, pstm, sql, params);
                BaseDao.closeResource(null, pstm, null);
            }
            return flag;
        }

        /**
         * 根据连接 用户Id 返回删除结果
         * @param connection
         * @param delId
         * @return
         * @throws Exception
         */
        public int deleteUserById(Connection connection, Integer delId) throws Exception {
            PreparedStatement preparedStatement = null;
            int flag = 0;
            if (null != connection) {
                String sql = "delete from smbms_user where id=?";
                Object[] params = {delId};
                flag = BaseDao.execute(connection, preparedStatement, sql, params);
                BaseDao.closeResource(null, preparedStatement, null);
            }
            return flag;
        }
    }
